package com.pactera.validator;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

@Component
public class ValidatorImpl implements InitializingBean {

    private Validator validator;


    @Override
    public void afterPropertiesSet() throws Exception {
        this.validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    public ValidationResult validate(Object bean) {
        final ValidationResult validationResult = new ValidationResult();
        Set<ConstraintViolation<Object>> constraintViolationsSet = validator.validate(bean);
        if ( constraintViolationsSet.size() > 0) {
            validationResult.setHasErrors(true);
            constraintViolationsSet.forEach(constraintViolations -> {
                String errorMsg = constraintViolations.getMessage();
                String propertyName = constraintViolations.getPropertyPath().toString();
                validationResult.getErrorMsgMap().put(propertyName,errorMsg);
            });
        }
        return validationResult;
     }
}
